          #!/usr/bin/python

"""Sends an init bomb to the master and sees how it copes over time.
 
Usage: init_bomb_test.py <HTTP_BASENAME>
Example: init_bomb_test.py http://localhost:8888
"""

import json
import sys
import threading
import time
import urllib2
import matplotlib.pyplot as plt


N = 100


class WorkerThread(threading.Thread):
    """A thread that retrieves a webpage, and documents it's end time and response contents.

    Attributes: i (given index in sequence) resp (the response text, str), end_time (floating point epoch time)
    """
    def __init__(self, i, base):
        self.i = i
        self._base = base
        self.resp = None
        self.end_time = None
        threading.Thread.__init__(self)

    def run(self):
        self.resp = urllib2.urlopen('%s/ajax?task=init' % self._base).read()
        self.end_time = time.time()


def main():
    if len(sys.argv) <= 1:
        print 'Usage: %s <HTTP_BASENAME>' % sys.argv[0]
        print 'Example: %s http://localhost:8888' % sys.argv[0]
        sys.exit()

    # Retrieve the HTTP base from the command line
    base = sys.argv[1]
    if base.endswith('/'):
        base = base[:-1]

    # Execute all the requests as threads
    threads = []
    for i in range(N):
        thread = WorkerThread(i, base)
        threads.append(thread)
    
    t0 = time.time()
    for thread in threads:
        thread.start()

    # Collect data as it comes in
    x = []
    y = []

    for thread in threads:
        thread.join()
        x.append(thread.i + 1)
        y.append(thread.end_time - t0)

    # Tailor the plot
    plt.plot(x, y, 'o')
    plt.xlabel('Session Init Call #')
    plt.ylabel('Response time (seconds)')
    plt.title('Results for init_bomb (N=%d)' % N)
    plt.grid(True)
    plt.show()


if __name__ == '__main__':
    main()

